import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/home' },
  { path: '/login', component: () => import('@/views/Login.vue') },
  { path: '/register', component: () => import('@/views/Register.vue') },
  {
    path: '/',
    component: () => import('@/views/home.vue'),
    children: [
      { path: '/home', component: () => import('@/views/chart/chart.vue') },
      { path: '/user-info', component: () => import('@/views/user/userInfo.vue') },
      { path: '/user-avatar', component: () => import('@/views/user/userAvatar.vue') },
      { path: '/user-pwd', component: () => import('@/views/user/userPwd.vue') },
      { path: '/art-cate', component: () => import('@/views/articlt/cate.vue') },
      { path: '/art-list', component: () => import('@/views/articlt/list.vue') }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 全局前置路由守卫
// 判断路由去向
router.beforeEach((to, from, next) => {
  if (to.path === '/login' || to.path === '/register') {
    next()
  } else {
    if (store.state.user.token) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
